package com.zjj.lbw.spring6.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import java.io.IOException;

public class ZjjLoginFilter extends HttpFilter {
    private final ObjectMapper objectMapper = new ObjectMapper();

    private AuthenticationManager authenticationManager;

    public ZjjLoginFilter(AuthenticationManager authenticationManager) {
        this.authenticationManager = authenticationManager;
    }


    @Override
    protected void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        if (!("/doLogin".equals(request.getServletPath()) && "POST".equalsIgnoreCase(request.getMethod()))) {
            chain.doFilter(request, response);
            return;
        }

        try {
            LoginRequest loginRequest = objectMapper.readValue(request.getInputStream(), LoginRequest.class);

            String username = loginRequest.getUsername();
            String password = loginRequest.getPassword();

            // 创建认证令牌
            UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

            Authentication authenticationResult = authenticationManager.authenticate(authRequest);

            // 登录成功
            successfulAuthentication(request, response, chain, authenticationResult);
        } catch (AuthenticationException ex) {
            // 登录失败
            unsuccessfulAuthentication(request, response, ex);
        }
    }


    private void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write("login fail, error:" + ex);
    }

    private void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authenticationResult) throws IOException {
        SecurityContextHolder.getContext().setAuthentication(authenticationResult);
        response.getWriter().write("login success, user:" + authenticationResult.getName());
    }
}
